package org.hyOnline.ebay
{
	import flash.events.*;
	import flash.net.*;

	public class XhrForEbay
	{
		public static const url:String = 'http://www.happyfashion.com.au/externalfile/ebayhelper.php';
		private var _productId:String,_productType:String;
		
		public function XhrForEbay(productId:String,productType:String)
		{
			_productId = productId;
			_productType = productType;
		}
		public function loadJSON(params:Object=null):void{
			var vars:URLVariables = new URLVariables();
			if(params!=null){
				for ( var name:String in params){
					vars[name] = params[name];
				}
			}
			vars.productId = _productId;
			vars.productType = _productType;
			var loader:URLLoader = new URLLoader();
			configureListeners(loader);
			var request:URLRequest = new URLRequest(url);
			request.method = URLRequestMethod.POST;
			request.data = vars;
			try {
				loader.load(request);
			} catch (error:Error) {
				trace("Unable to load requested document.");
			}
		}
		private function configureListeners(dispatcher:IEventDispatcher):void {
			dispatcher.addEventListener(Event.COMPLETE, completeHandler);
			dispatcher.addEventListener(Event.OPEN, openHandler);
			dispatcher.addEventListener(ProgressEvent.PROGRESS, progressHandler);
			dispatcher.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
			dispatcher.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler);
			dispatcher.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
		}
		
		private function completeHandler(event:Event):void {
			var loader:URLLoader = URLLoader(event.target);
			try{
				var data:Object = JSON.parse(loader.data);
				JsForHfash.feedJSON(data);
			}catch(error:Error){
				//JsForHfash.println("Unable to parse json");
				JsForHfash.println(loader.data);
			}
			
		}
		private function openHandler(event:Event):void {
			trace("openHandler: " + event);
		}
		
		private function progressHandler(event:ProgressEvent):void {
			trace("progressHandler loaded:" + event.bytesLoaded + " total: " + event.bytesTotal);
		}
		
		private function securityErrorHandler(event:SecurityErrorEvent):void {
			trace("securityErrorHandler: " + event);
		}
		
		private function httpStatusHandler(event:HTTPStatusEvent):void {
			trace("httpStatusHandler: " + event);
		}
		
		private function ioErrorHandler(event:IOErrorEvent):void {
			trace("ioErrorHandler: " + event);
		}
	}
}